import base64
import json
import cv2
import numpy as np
from django.conf import settings
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from .exceptions import ClientError

from channels.consumer import SyncConsumer,AsyncConsumer
from asgiref.sync import sync_to_async
from channels.exceptions import StopConsumer
from channels.generic.websocket import JsonWebsocketConsumer
class EchoConsumer(JsonWebsocketConsumer):

    def websocket_connect(self, event):
        # print('1')
        self.accept()

    def websocket_receive(self, event):
        # print('2')
        self.send(json.dumps({
            "type": "websocket.send supcon",
            "text": event["text"],
        }))


    def websocket_message(self, event):
        # print('3')
        self.send(json.dumps({
            "type": "websocket.send jackie",
            "text": event["text"],
        }))

    def websocket_disconnect(self, event):
        # print('4')
        self.send(json.dumps({
            "type": "websocket.send",
            # "text": event.get("text",default=""),
        }))

class ChatConsumer(AsyncJsonWebsocketConsumer):
    """
    This chat consumer handles websocket connections for chat clients.

    It uses AsyncJsonWebsocketConsumer, which means all the handling functions
    must be async functions, and any sync work (like ORM access) has to be
    behind database_sync_to_async or sync_to_async. For more, read
    http://channels.readthedocs.io/en/latest/topics/consumers.html
    """

    ##### WebSocket event handlers

    async def connect(self):
        """
        Called when the websocket is handshaking as part of initial connection.
        """
        await self.accept()
        self.rooms = set()

    async def websocket_receive(self, content, **kwargs):
        """
        Called when we get a text frame. Channels will JSON-decode the payload
        for us and pass it as the first argument.
        """
        # Messages will have a "command" key we can switch on

        # print(base64.b64encode(content['bytes']).decode())
        try:
            # TODO:美颜系统
            # 接收前端视频数据
            nparr = np.fromstring(content['bytes'], np.uint8)
            # 解码前端视频数据
            image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

            #TODO:图像处理

            # print(content)
            # height, width = image.shape[:2]
            # size = (int(width * 0.5), int(height * 0.5))
            # shrink = cv2.resize(image, size, interpolation=cv2.INTER_AREA)
            # image_hsv = cv2.cvtColor(shrink, cv2.COLOR_BGR2HSV)
            # content['bytes'] = cv2.imencode('.bmp', image_hsv)[1]
            image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

            # 编码图像数据
            content['bytes'] = cv2.imencode('.jpg', image_hsv)[1]
            # content['bytes'] = cv2.imencode('.jpg', image)[1]


            # 异步返回数据
            await self.send(base64.b64encode(content['bytes']).decode())
        except Exception as e:
            print(e)


    async def disconnect(self, code):
        """
        Called when the WebSocket closes for any reason.
        """
        # Leave all the rooms we are still in
